using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
using JMClient.Models.Data;
using JMClient.Models.PhysicalComponents;
using JMClient.Service;
using JMClient.Views;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace JMClient.ViewModels;

public class ComponentsListViewModel : BindableBase
{
    private readonly IEventAggregator _ea;
    private SubscriptionToken _token;
    private readonly IDialogService _dialogService;
    private readonly IContainerProvider _container;
    private readonly IRegionManager _regionManager;
    private bool _opening;
    private CancellationTokenSource? _cts;
    private DeviceEntityViewModel? _selectedDevice;
    public ObservableCollection<DeviceEntityViewModel> Devices { get; set; }
    
    // public ICommand HandleSelectionCommand => new DelegateCommand<DeviceEntityViewModel>(async (selected) =>
    // {
    //     await HandleSelectionAsync(selected);
    // });

    
     public DeviceEntityViewModel? SelectedDevice
    {
        get => _selectedDevice;
        set
        {
            if (SetProperty(ref _selectedDevice, value))
            {
                if (_selectedDevice?.Name == null)
                {
                    return; 
                }
                // Fire-and-forget safe call
                //暂时修改为事件通知 不再使用自己的事件了
                //_ = HandleSelectionAsync(_selectedDevice);
                // 清空选择，确保下次点击同一项也能触发
                this.SelectedDevice = null;
            }
        }
    }
    
    public ComponentsListViewModel(IEventAggregator eventAggregator,IRegionManager  regionManager,IDialogService dialogService,IContainerProvider container)
    {
        _ea = eventAggregator;
        _token = _ea.GetEvent<TriggerParentEvent>()
            .Subscribe(OnChildNotified,
                ThreadOption.UIThread,
                keepSubscriberReferenceAlive: false);
        
        this._dialogService = dialogService;
        this._container = container;
        _regionManager = regionManager;
        var sample = new List<DeviceEntity>();
            try
            {
                using (var context = new DeviceDbContext())
                {
                    foreach (var data in context.Devices.ToList())
                    {
                        sample.Add(data);
                    }
                    // 新增一条数据
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        Devices = new ObservableCollection<DeviceEntityViewModel>();

        foreach (var e in sample)
        {
            var aDevice = container.Resolve<DeviceEntityViewModel>();
            aDevice.Entity = e;
          Devices.Add(aDevice);  ;
        }
           // Devices.Add(new DeviceEntityViewModel(regionManager, dialogService));
    }
    public Task HandleSelectionAsync(DeviceEntityViewModel? selected)
    {
        if (selected?.Name is null) 
            return Task.CompletedTask;

        // 防止重复触发（对于同一设备可以打开多个，但需要防止快速重复点击）
        if (_opening) return Task.CompletedTask;
        _opening = true;

        // 取消上一次的等待（如有）
        _cts?.Cancel();
        _cts?.Dispose();
        _cts = new CancellationTokenSource();
        var ct = _cts.Token;

        try
        {
            // 1) 通过容器创建一个对话 VM
            var dialogVm = _container.Resolve<SandboxWindowViewModel>();
            dialogVm.DeviceEntity = selected.Entity;
            var scopedRegionManager = _regionManager.CreateRegionManager();
            // 2) 把实例放到参数里，确保对话使用此 VM 实例
            var parameters = new DialogParameters
            {
                { "width", 900 },
                { "height", 600 },
                { "viewModelInstance", dialogVm },
                { "scopedRegionManager", scopedRegionManager },
                { "entity", selected.Entity },
                { "title", $"部件 - {selected.Entity.Name}" }
            };
            // 3) 使用非模态方式显示对话框
            _dialogService.Show("SandboxWindow", parameters, result =>
            {
                // 对话框关闭时的回调（非模态对话框关闭时执行）
                _opening = false;
                // 可以在这里处理对话框关闭后的逻辑
                Console.WriteLine($"沙箱对话框已关闭: {selected.Entity.Name}");
            });

            // 4) 等待对话框初始化完成（非阻塞的）
           // await dialogVm.Ready.WaitAsync(CancellationToken.None);

            // 5) 对话已渲染完毕，此处可安全做后续区域渲染或 Region 导航
                    // 5) 对话框已渲染完毕，可以安全执行后续操作
            // // 注意：由于是非模态，用户可以同时操作主界面和对话框
           Console.WriteLine($"沙箱对话框已就绪: {selected.Entity.Name}");
            _opening = false;
        }
        catch (OperationCanceledException) { /* 取消逻辑，可忽略 */ }
        catch (Exception ex)
        {
            // 记录或通知用户
            Console.WriteLine(ex);
        }
        finally
        {
            _opening = false;
            //SelectedDevice = null; // 允许再次选择同一项
        }

        return Task.CompletedTask;
    }
    private void OnChildNotified(object message)
    {
        _ = HandleSelectionAsync(message as DeviceEntityViewModel);
        // 收到子组件通知后的处理
        
    }

}